<template>
  <!-- 导入表 -->
  <el-dialog
    v-model="showModal"
    :width="620"
    :footer="null"
    :maskClosable="false"
    :title="'从Excel导入' + title"
    :bodyStyle="{padding:0}"
  >
    <template v-if="!result">
      <el-upload
        v-decorator="['file', {rules: [{required: true, message:'请选择excel文件'}]}]"
        name="file"
        accept=".xlsx"
        listType="picture"
        class="drag-upload"
        :loading="loading"
        :fileList="fileList"
        :remove="removeFile"
        :beforeUpload="beforeUpload"
        @reject="formatReject"
      >
        <div class="upload-drag" v-if="fileList.length === 0">
          <svg class="svg-content" viewBox="0 0 100% 100%" preserveAspectRatio="none">
            <rect
              class="svg-rect"
              stroke-dasharray="8 8"
              stroke-opacity="0.9"
              x="1.5"
              y="1.5"
              rx="8"
              ry="6"
              style="fill: #fff;stroke: rgba(93,110,164,0.5);stroke-width: 1.5px;fill-opacity: 0.1;"
            />
          </svg>
          <p class="ant-upload-drag-icon">
            <img
              class="result-icon"
              style="color: rgba(93,110,164,0.5); font-size: 48px;"
              src="@/assets/icons/add-upload.svg"
            />
          </p>
          <p class="ant-upload-hint-prompt">将表格文件托至此处或者点击+选择文件</p>
        </div>
        <div v-if="fileList.length">
          <div class="upload-drag" v-if="loading">
            <svg class="svg-content" viewBox="0 0 100% 100%" preserveAspectRatio="none">
              <rect
                class="svg-rect"
                stroke-dasharray="8 8"
                stroke-opacity="0.9"
                x="1.5"
                y="1.5"
                rx="8"
                ry="6"
                style="fill: #fff;stroke: rgba(93,110,164,0.5);stroke-width: 1.5px;fill-opacity: 0.1;"
              />
            </svg>
            <div class="holder-loading">
              <a-icon class="preview-icon-loading" :component="uploadLoading" spin />
              <p>{{ uploadText }}</p>
            </div>
          </div>

          <div class="place-holder" v-else>
            <div v-if="showError" class="format-error">
              <a-icon type="exclamation-circle" />
              <p>请上传xlsx格式的文件</p>
            </div>

            <div v-if="fileList[0]" class="file-preview">
              <svg class="svg-content" viewBox="0 0 100% 100%" preserveAspectRatio="none">
                <rect
                  class="svg-rect"
                  stroke-dasharray="8 8"
                  stroke-opacity="0.9"
                  x="2"
                  y="2"
                  rx="8"
                  ry="6"
                  style="fill: #fff;stroke: rgba(93,110,164,0.5);stroke-width: 1.5px;fill-opacity: 0.1;"
                />
              </svg>
              <div class="file-cls">
                <img class="preview-icon" src="@/assets/icons/in-excel-preview.svg" />
                <span class="file-tit">{{ fileList[0].name }}</span>
              </div>
              <a-tooltip class="preview-delete" placement="topRight" @click.stop="removeFile">
                <fw-icon type="deleteIcon" />
              </a-tooltip>
            </div>
          </div>
        </div>
      </el-upload>

      <div class="help-tips" v-if="fileUrls.length===0 && fileList.length===0">
        <span style="color: #D8D8D8;">如您没有表格模板，请先下载：</span>
        <a
          class="user-link"
          target="_blank"
          :href="fileUrl"
          :download="'导入'+title+'数据模板.xlsx'"
        >{{ `${text}导入模板.xlsx` }}</a>
      </div>

      <div class="help-tips" v-if="fileUrls.length>0 && fileList.length===0">
        <span style="color: #D8D8D8;">如您没有表格模板，请先下载：</span>
        <a-space direction="vertical" style="text-align: left;">
          <a
            class="user-link"
            v-for="(item, idx) in fileUrls"
            target="_blank"
            :key="idx"
            :href="item"
            :download="'导入'+titles[idx]+'数据模板.xlsx'"
          >{{ `${titles[idx]}导入模板.xlsx` }}</a>
        </a-space>
      </div>

      <div class="btn-main" v-if="fileList.length">
        <el-button
          :disabled="fileList.length < 1"
          style="width: 110px"
          type="primary"
          @click="uploadFile"
          :loading="loading"
        >导 入</el-button>
      </div>
    </template>

    <div v-else class="result drag-upload">
      <div v-if="!result.duplicated_lines && !result.errors">
        <div class="upload-drag">
          <svg class="svg-content" viewBox="0 0 100% 100%" preserveAspectRatio="none">
            <rect
              class="svg-rect"
              stroke-dasharray="8 8"
              stroke-opacity="0.9"
              x="1.5"
              y="1.5"
              rx="8"
              ry="6"
              style="fill: #fff;stroke: rgba(93,110,164,0.5);stroke-width: 1.5px;fill-opacity: 0.1;"
            />
          </svg>
          <img class="result-icon" src="@/assets/icons/done.svg" />
          <p class="success-tips">全部导入完成</p>
          <p>·成功导入{{ result.success_cnt }}条信息</p>
        </div>

        <div class="btn-main">
          <el-button style="width: 110px" type="primary" @click="hide">确 定</el-button>
        </div>
      </div>
      <div class v-else>
        <div class="errors" v-if="result.error_cnt">
          <div class="result-head">
            <div class="res-tit">
              <img class="result-icon" src="@/assets/icons/upload-error.svg" />
              <div class="tit">错误提示</div>
            </div>
            <a-button style="width: 110px" type="primary" @click="doCopy" ghost>复制错误提示</a-button>
          </div>
          <div class="result-col">
            <svg class="svg-content" viewBox="0 0 100% 100%" preserveAspectRatio="none">
              <rect
                class="svg-rect"
                stroke-dasharray="8 8"
                stroke-opacity="0.9"
                x="1.5"
                y="1.5"
                rx="8"
                ry="6"
                style="fill: #fff;stroke: rgba(93,110,164,0.5);stroke-width: 1.5px;fill-opacity: 0.1;"
              />
            </svg>
            <div class="result-main">
              <div>·错误信息{{ result.error_cnt }}条</div>
              <div class="red" v-for="(item,index) in result.errors" :key="index">
                {{ index+1 }}.
                第{{ item.lines.join(',') }}行
                {{ item.error }}
              </div>
            </div>
          </div>
        </div>
        <div class="errors" v-if="result.duplicated_lines">
          <div class="result-head">
            <div class="res-tit">
              <img class="result-icon" src="@/assets/icons/upload-warning.svg" />
              <div class="tit">重复提示</div>
            </div>
          </div>
          <div class="result-col">
            <svg class="svg-content" viewBox="0 0 100% 100%" preserveAspectRatio="none">
              <rect
                class="svg-rect"
                stroke-dasharray="8 8"
                stroke-opacity="0.9"
                x="1.5"
                y="1.5"
                rx="8"
                ry="6"
                style="fill: #fff;stroke: rgba(93,110,164,0.5);stroke-width: 1.5px;fill-opacity: 0.1;"
              />
            </svg>
            <div class="result-main">
              <div>·重复信息{{ result.duplicated_cnt }}条</div>
              <div class="red">1. 第{{ result.duplicated_lines.join(',') }}行信息重复</div>
            </div>
          </div>
        </div>
        <div class="errors">
          <div class="result-head">
            <div class="res-tit">
              <img class="result-icon" src="@/assets/icons/done.svg" />
              <div class="tit">成功导入</div>
            </div>
          </div>
          <div class="result-main result-main-scss">
            <svg class="svg-content" viewBox="0 0 100% 100%" preserveAspectRatio="none">
              <rect
                class="svg-rect"
                stroke-dasharray="8 8"
                stroke-opacity="0.9"
                x="1.5"
                y="1"
                rx="8"
                ry="6"
                style="fill: #fff;stroke: rgba(93,110,164,0.5);stroke-width: 1.5px;fill-opacity: 0.1;"
              />
            </svg>
            <div>·成功导入{{ result.success_cnt }}条信息</div>
          </div>
        </div>
        <div class="btn-main">
          <a-button
            style="width: 110px;margin-right:12px"
            ghost
            type="primary"
            @click="reUpload"
          >重新上传</a-button>
          <a-button style="width: 110px;margin-left:12px" type="primary" @click="hide">确 定</a-button>
        </div>
      </div>
    </div>
  </el-dialog>
</template>
<script>
import { uploadLoading } from '@/core/icons'
export default {
  name: 'ImportLocationModal',
  data () {
    return {
      uploadText: '正在上传...',
      uploadLoading,
      showModal: false,
      showError: false,
      uploadApi: null,
      loading: false,
      result: null,
      fileList: [],
      fileUrl: '',
      title: '',
      text: '',
      fileUrls: [],
      titles: []
    }
  },
  methods: {
    show (item, api, uploadApi) {
      this.removeFile()
      this.result = null
      this.fileUrls = []
      this.showModal = true
      this.title = item.label
      this.text = item.text || item.label
      this.uploadApi = uploadApi
      this.uploadText = '正在上传...'
      api && this.getTplUrl(api)
    },
    doCopy () {
      let message = ''
      if (this.result.error_cnt) {
        const errInfo = this.result.errors.map((element, index) => {
          return `${index + 1}.第${element.lines.join(',')}行${element.error}\n`
        })
        message += `·错误信息${this.result.error_cnt}条\n${errInfo.join('\n')}`
      }
      if (this.result.duplicated_cnt) {
        message = `${message}\n·重复信息${this.result.duplicated_cnt}条\n1. 第${this.result.duplicated_lines.join(',')}行信息重复`
      }
      const that = this
      this.$copyText(message).then(function (e) {
        that.$message.success('复制成功')
      }, function (e) {
        that.$message.error('复制失败')
      })
    },
    getTplUrl (api) {
      if (Array.isArray(api)) {
        this.titles = api.map(item => item.name)
        Promise.all(api.map(item => item.api)).then(res => {
          this.fileUrls = res.map(item => window.URL.createObjectURL(item))
        })
      } else {
        api.then(res => {
          this.fileUrl = window.URL.createObjectURL(res)
        })
      }
    },
    reUpload () {
      this.fileList = []
      this.result = null
    },
    hide () {
      this.showModal = false
      this.$message.success(`您成功导入${this.result.success_cnt}条信息`)
    },
    removeFile () {
      this.fileList = []
    },
    formatReject () {
      this.showError = true
      setTimeout(() => {
        this.showError = false
      }, 3000)
    },
    beforeUpload (file, fileList) {
      if (file.size / 1000 / 1000 > 20) {
        this.$message.info(`请上传不超过20M的文件`)
        return
      }
      this.fileList = fileList.slice(-1)

      return false
    },
    uploadFile () {
      this.loading = true
      setTimeout(() => {
        this.uploadText = '表格数据解析中...'
      }, Math.random() * 2000)

      const formData = new FormData()
      if (this.fileList && this.fileList[0]) {
        formData.append('file', this.fileList[0])
      }
      if (Object.keys(this.uploadApi.data).length) {
        Object.keys(this.uploadApi.data).forEach(item => {
          formData.append(item, this.uploadApi.data[item])
        })
      }
      this.uploadApi.api(formData, this.uploadApi.data).then(res => {
        this.loading = false
        this.result = res.data || null
        if (res.code === 200) {
          //   this.$message.success('导入完成')
          this.$emit('ok')
        } else {
          this.$message.error(res.msg)
        }
      }).catch((err) => {
        this.loading = false
        this.$message.error(err.message)
      })
    }
  }
}
</script>

<style lang="scss" scoped>
:deep(.svg-content) {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}
:deep(.result-col) {
  position: relative;
  width: 443px;
  margin: 0 auto;
}
:deep(.svg-rect) {
  width: calc(100% - 3px);
  height: calc(100% - 3px);
}
:deep(.drag-upload) {
  text-align: center;
  position: relative;
  display: block;
  .upload-drag {
    width: 440px;
    height: 250px;
    margin: 5px auto 30px;
    padding-top: 40px;
    background: rgba(93, 110, 164, 0.06);
    border-radius: 4px;
    position: relative;
    .ant-upload-hint-prompt {
      font-size: 14px;
      color: #282828;
    }
  }
  .preview-icon-loading {
    font-size: 48px;
    margin: 12px 0 48px;
  }
  .place-holder {
    border-radius: 4px;
    position: relative;
    background: rgba(93, 110, 164, 0.06);
    height: 94px;
    width: 440px;
    margin: 48px auto 124px;
    .format-error {
      background: #ffe6e6;
      border-radius: 2px;
      border: 1px solid #ff8f8f;
      color: #595959;
      padding-top: 30px;
      .anticon {
        color: red;
        font-size: 25px;
        padding-bottom: 20px;
      }
    }
    .file-preview {
      display: flex;
      height: 100%;
      position: relative;
      border-radius: 4px;
      color: #bababa;
      font-size: 14px;
      padding: 0 16px;
      display: flex;
      justify-content: center; /* 水平居中 */
      align-items: center; /* 垂直居中 */
      .file-cls {
        flex: 1;
        text-align: left;
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
      }
      .preview-icon {
        height: 54px;
        margin-right: 16px;
        position: relative;
        z-index: 10;
      }
      .file-tit {
        font-size: 16px;
        color: #282828;
      }
      .preview-delete {
        color: #ff4d4f;
        cursor: pointer;
        width: 30px;
        height: 30px;
        background: #fff;
        border-radius: 50%;
        display: flex;
        position: relative;
        z-index: 10;
        justify-content: center; /* 水平居中 */
        align-items: center; /* 垂直居中 */
      }
    }
    .holder-loading {
      .ant-spin-spinning {
        line-height: 3.5;
        font-size: 30px;
      }
      .ant-spin-dot {
        font-size: 28px;
      }
    }
  }
  .ant-upload.ant-upload-drag {
    background: transparent;
    border: none;
    .ant-upload {
      padding-top: 40px;
    }
    p.ant-upload-drag-icon {
      margin: 14px 0 48px;
    }
  }

  .ant-upload-list-picture {
    display: none;
  }
}
:deep(.btn-main) {
  text-align: center;
  padding: 0 0 30px 0;
}
:deep(.result) {
  font-size: 16px;
  font-weight: 400;
  color: #595959;
  line-height: 22px;
  padding-top: 40px;
  .result-icon {
    padding: 0 0 10px;
  }
  .errors {
    margin-bottom: 40px;
  }
  .result-main {
    &.result-main-scss {
      height: 58px;
      min-height: 58px;
      max-height: 58px;
      display: flex;
      align-items: center; /* 垂直居中 */
    }
    width: 440px;
    min-height: 120px;
    max-height: 220px;
    overflow-y: scroll;
    padding-bottom: 2px;
    background: rgba(93, 110, 164, 0.06);
    border-radius: 4px;
    position: relative;
    text-align: left;
    margin: 0 auto;
    padding: 8px;
    font-size: 16px;
    color: #595959;
    .red {
      color: #ff4d4f;
      word-break: break-all;
    }
  }
  .result-head {
    display: flex;
    width: 440px;
    margin: 0 auto;
    justify-content: center; /* 水平居中 */
    align-items: center; /* 垂直居中 */
    margin-bottom: 12px;
    .res-tit {
      flex: 1;
      text-align: left;
      display: flex;
      align-items: center; /* 垂直居中 */
      .result-icon {
        width: 26px;
        height: 26px;
        padding: 0;
        margin-right: 12px;
      }
    }
  }
  .success-tips {
    font-size: 24px;
    font-weight: 700;
    color: #282828;
    margin-bottom: 65px;
  }
  ul {
    padding-top: 30px;
    margin-block-start: 0;
    padding-inline-start: 24px;
    li {
      text-align: left;
      margin-bottom: 7px;
    }
  }
  .result-error {
    min-height: 100px;
    box-shadow: 0px 0px 3px 0px rgba(0, 0, 0, 0.1);
    text-align: left;
    padding: 8px 7px;
    color: #ff4d4f;
    max-height: 200px;
    overflow: auto;
    user-select: text;
  }
}
:deep(.help-tips) {
  padding: 0 0 36px;
  text-align: center;
  font-size: 14px;
}
</style>
